package com.jeady.timetodo.activities.setting

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.provider.Settings
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material.icons.outlined.Share
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jeady.jxcompose.ClickEffect.longClickSaveToDCIM
import com.jeady.jxcompose.GitManager
import com.jeady.jxcompose.TipDisplay
import com.jeady.jxcompose.Utils
import com.jeady.jxcompose.showTip
import com.jeady.timetodo.R
import com.jeady.timetodo.activities.unlocked
import com.jeady.timetodo.base.Title
import com.jeady.timetodo.base.showToast
import com.jeady.timetodo.manager.Authentication
import com.jeady.timetodo.services.RunningService
import java.io.File

private val TAG = "[SettingItem] "

private var settingPin by mutableStateOf(false)

@Composable
fun SettingUI() {
    LazyColumn(Modifier.padding(10.dp)){
        item{
            SettingProfile()
        }
        item {
            SettingAppLock()
        }
        item {
            SettingOthers()
        }
    }
}

@Composable
fun SupportAndDonate() {
    val context = LocalContext.current
    val elevation = remember { RoundedCornerShape(20.dp) }
    Surface(Modifier.padding(0.dp, 10.dp), shadowElevation = 2.dp, shape = elevation) {
        Column(
            Modifier.padding(10.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
            Title("公众号留下你想要的功能/问题", "长按图片保存", Modifier.padding(start = 10.dp))
            Image(
                painter = painterResource(id = R.drawable.gzh),
                contentDescription = "关注公众号",
                Modifier.longClickSaveToDCIM(context, R.drawable.gzh)
            )
            val pagesId = listOf(
                R.drawable.zhufubao,
                R.drawable.szrmb,
                R.drawable.zsm,
                R.drawable.weixin,
            )
            LazyRow(horizontalArrangement = Arrangement.spacedBy(5.dp)) {
                items(pagesId){
                    Image(
                        modifier = Modifier
                            .width(80.dp)
                            .height(120.dp)
                            .clip(elevation)
                            .longClickSaveToDCIM(context, it),
                        painter = painterResource(it),
                        contentDescription = "捐助开发者",
                        contentScale = ContentScale.FillHeight
                    )
                }
            }
        }
    }
}
private var displaySupport by mutableStateOf(true)
@Composable
fun SettingOthers(){
    val context = LocalContext.current
    Column(Modifier.padding(top = 10.dp)) {
        Title("其他APP设置", "", Modifier.padding(start = 10.dp))
        SettingItemButton("停止后台服务"){
            context.stopService(Intent(context, RunningService::class.java))
        }
        SettingItemButton("立即锁定"){
            unlocked = false
            showToast(context, "设置成功")
        }
        SettingItemButton("[APP保活]设置自启动"){
            showTip("即将打开APP设置页面，请进行如下操作以防止APP被系统杀死而无法执行任务：\n" +
                    "1. 找到并开启‘自启动’\n" +
                    "2. 找到省电策略，并设置为‘无限制’\n" +
                    "以上设置仅在小米手机上进行了验证，如有其他问题，请公众号留言",
                "取消", "去设置"){
                if(it){
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    intent.data = Uri.parse("package:${context.packageName}")
                    context.startActivity(intent)
                }
            }
        }
        SettingItemContainer {
            // 显示app版本
            val versionName = context.packageManager.getPackageInfo(context.packageName, 0).versionName
            Box(Modifier.padding(10.dp)) {
                Text("版本版本：$versionName")
            }
        }
        if(displaySupport){
            SupportAndDonate()
        }
    }
}

@Composable
fun SettingAppLock() {
    val context = LocalContext.current
    val preferences = context.getSharedPreferences("timeToDo", ComponentActivity.MODE_PRIVATE)
    var needUnlock by remember {
        mutableStateOf(
            preferences.getBoolean("needUnlock", true)
        )
    }
    var useSystemUnlock by remember {
        mutableStateOf(
            preferences.getBoolean("useSystemUnlock", false)
        )
    }
    var useAppPinUnlock by remember {
        mutableStateOf(
            preferences.getString("appPinCode", "")?.isNotEmpty()?:false
        )
    }
    Column(Modifier.padding(top = 10.dp)) {
        Title("隐私与安全", "")
        SettingItemSwitch("打开App时需要解锁?", needUnlock) {
            needUnlock = it
            if (it) {
                preferences.edit().putBoolean("needUnlock", true).apply()
                showTip("开启成功")
            } else {
                preferences.edit().putBoolean("needUnlock", false).apply()
                showTip("关闭成功")
            }
        }
        SettingItemSwitch("使用系统验证?", useSystemUnlock, needUnlock) {
            useSystemUnlock = it
            if (it) {
                showTip("测试系统验证是否可用", "取消", "验证") {
                    if (it) {
                        Authentication.finger(context, context.mainExecutor) {
                            if (it) {
                                preferences.edit().putBoolean("useSystemUnlock", true)
                                    .apply()
                                showTip("验证成功", secondToClose = 3)
                            } else {
                                preferences.edit().putBoolean("useSystemUnlock", false)
                                    .apply()
                                showTip("验证失败")
                                useSystemUnlock = false
                            }
                        }
                    } else {
                        showTip("验证失败")
                        useSystemUnlock = false
                    }
                }
            } else {
                preferences.edit().putBoolean("useSystemUnlock", false).apply()
                useSystemUnlock = false
                showTip("关闭系统验证")
            }
        }
        SettingItemSwitch("设置APP自带PIN码", useAppPinUnlock, needUnlock) {
            if (it) {
                settingPin = true
            } else {
                preferences.edit().putString("appPinCode", "").apply()
                showTip("Pin码已清空")
                useAppPinUnlock = false
            }
        }
        LaunchedEffect(settingPin) {
            if (!settingPin) {
                useAppPinUnlock =
                    preferences.getString("appPinCode", "")?.isNotEmpty() ?: false
            }
        }
    }
}

@Composable
fun SettingItemSwitch(title: String, state: Boolean, enabled: Boolean=true, onSwitch: (Boolean)->Unit){
    SettingItemContainer {
        Row(
            Modifier
                .fillMaxWidth()
                .padding(10.dp, 0.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(title)
            Switch(checked = state, onCheckedChange = onSwitch, enabled=enabled)
        }
    }
}

@Composable
fun SettingItemButton(title: String, img:  ImageVector?=null, onIconClicked: (()->Unit)?=null, onClicked: (()->Unit)?=null){
    SettingItemContainer(){
        Row(Modifier
            .fillMaxWidth()
            .clickable(onClicked != null) { onClicked?.invoke() }
            .padding(10.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ){
            Text(title)
            img?.let {
                Icon(it, "goto",
                    Modifier
                        .fillMaxHeight(0.9f)
                        .clickable(onIconClicked != null) {
                            onIconClicked?.invoke()
                        }
                )
            }
        }
    }
}

@Composable
fun SettingItemContainer(modifier: Modifier=Modifier, content: @Composable BoxScope.()->Unit){
    Surface(
        modifier
            .fillMaxWidth()
            .height(50.dp),
        shadowElevation = 1.dp
    ){
        Box(Modifier, contentAlignment = Alignment.CenterStart){
            content()
        }
    }
}

@Composable
fun SettingFullScreen(){
    val context = LocalContext.current
    val preferences = context.getSharedPreferences("timeToDo", ComponentActivity.MODE_PRIVATE)
    if(settingPin) {
        Authentication.PinManager(confirmText = "设置") {
            if (it.isNotEmpty()) {
                preferences.edit().putString("appPinCode", it).apply()
                showTip(
                    "设置PIN码成功，请记牢 '$it'.",
                    confirmButtonText = "已记住，小意思"
                )
            } else {
                showToast(context, "未更改")
            }
            settingPin = false
        }
    }
    TipDisplay()
}

@Composable
fun SettingProfile(){
    val context = LocalContext.current
    Surface(shadowElevation = 2.dp) {
        Column(Modifier.padding(10.dp)) {
            Row(
                Modifier
                    .fillMaxWidth()
                    .height(50.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row{
                    Image(
                        painterResource(R.drawable.icon),
                        contentDescription = "头像",
                        Modifier
                            .size(50.dp)
                            .clip(CircleShape)
                    )
                    Column(
                        Modifier
                            .padding(start = 5.dp)
                            .clickable {
                                val clipboardManager =
                                    context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                                clipboardManager.setPrimaryClip(
                                    ClipData.newPlainText(
                                        "mp",
                                        "微代码人生"
                                    )
                                )
                                showTip("公众号名称已复制")
                            }) {
                        Text("探索者阿迪", fontWeight = FontWeight.SemiBold)
                        Text("公众号《微代码人生》", fontSize = 12.sp)
                    }
                }
//                Icon(Icons.Outlined.Share, "Enter",
//                    Modifier
//                        .fillMaxHeight(0.9f)
//                        .background(Color.LightGray)
//                        .clickable {
//                            // 跳转到指定公众号
//                            try {
//                                val intent = Intent(Intent.ACTION_VIEW)
////                            intent.data = Uri.parse("weixin://dl/officialaccount?officialAccountID=gh_11291a6f3134")
////                            intent.data = Uri.parse("weixin://dl/business/?ticket=microcodelife")
//                                intent.data =
//                                    Uri.parse("weixin://dl/business/?ticket=gh_11291a6f3134")
//                                context.startActivity(intent)
//                            } catch (e: Exception) {
//                                showTip("未安装微信")
//                            }
//                        }
//                )
            }
            HorizontalDivider()
            SettingItemButton("分享APP下载链接", Icons.Outlined.Share){
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "text/plain"
                intent.putExtra(Intent.EXTRA_TEXT, "一个炒鸡实用的定时APP, 下载地址: \nhttps://www.123pan.com/s/0iBIjv-Pyfvd.html")
                context.startActivity(Intent.createChooser(intent, "分享"))
            }
            HorizontalDivider()
            SettingItemButton("检查更新", Icons.Outlined.Refresh){
                checkNewVersion(context)
            }
            HorizontalDivider()
        }
    }
}

fun checkNewVersion(context: Context) {
    val downloadDir: String = run {
        val downloadDir =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path
        var saveDir = downloadDir + "/" + context.packageName
        if (!File(saveDir).exists()) {
            if (!File(saveDir).mkdirs()) {
                saveDir = downloadDir
            }
        }
        saveDir
    }
    var apkPath by mutableStateOf("$downloadDir/release.apk")
    val gitManager = GitManager("jeady5", "publisher", "3978ad8a52f28197a37472381e8e8bfb")
    fun downloadFinish(state: String) {
        val validState = state.endsWith(".apk") && File(state).exists()
        showTip(
            "下载结束: $state",
            if (validState) "忽略" else "知道了",
            if (validState) "安装" else ""
        ) {
            if (it) {
                gitManager.openAPK(context, state)
            }
        }
    }
    gitManager.getLatestServerVersion("timetodo/versions.json") {it, err->
        err?.let {
            showTip("检查失败： $err")
            return@getLatestServerVersion
        }
        it?.let { v ->
            val appVersion = context.packageManager.getPackageInfo(
                context.packageName,
                0
            ).versionName
            Log.d(TAG, "About: check version new: ${v.version}; old: $appVersion")
            if (v.version > appVersion) {
                showTip(
                    "${v.appLabel}最新版本：${v.version}\n${v.description}",
                    "忽略",
                    "下载"
                ) {
                    if (it) {
                        val downloadPath =
                            "$downloadDir/${v.appLabel}_${v.version}.apk"

                        fun download() {
                            gitManager.downloadFile(
                                v.downloadUrl,
                                downloadPath
                            ) { res ->
                                apkPath = res
                                downloadFinish(res)
                            }
                            showTip("下载中，请稍等...")
                        }
                        if (File(downloadPath).exists()) {
                            showTip(
                                "文件已经存在，想要重新下载吗？",
                                "重新下载",
                                "直接安装"
                            ) {
                                if (it) {
                                    gitManager.openAPK(context, downloadPath)
                                } else {
                                    download()
                                }
                            }
                        } else {
                            download()
                        }
                    }
                }
            } else {
                showTip("当前已是最新版本 $appVersion ${v.version}")
            }
        } ?: Utils.showToast(context, "检查失败")
    }
}